package org.example.demo1.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.example.demo1.service.PodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;


//封装对k8s集群的Pod的操作
@RestController
@Slf4j
@RequestMapping("/api/k8s")
public class K8sController {

    @Autowired
    PodService podservice;

    private static final String KUBECONFIG_PATH = "E:\\whu-ops\\src\\main\\resources\\templates\\config";


    /**
     * 查看Pod详情（describe）
     * @param podName Pod名称
     * @param namespace 命名空间（可选）
     * @return Pod详情信息
     */
    @GetMapping("/pods/{podName}/describe")
    public ResponseEntity<Map<String, Object>> describePod(
            @PathVariable String podName,
            @RequestParam(required = false) String namespace) {
        try {
            Map<String, Object> podDetails = podservice.describePod(podName, namespace);
            return ResponseEntity.ok(podDetails);
        } catch (Exception e) {
            log.error("获取Pod详情失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", "获取Pod详情失败: " + e.getMessage()));
        }
    }

    /**
     * 重启Pod
     * @param podName Pod名称
     * @param namespace 命名空间（可选）
     * @return 操作结果
     */
    @PostMapping("/pods/{podName}/restart")
    public ResponseEntity<Map<String, Object>> restartPod(
            @PathVariable String podName,
            @RequestParam(required = false) String namespace) {
        try {
            Map<String, Object> result = podservice.restartPod(podName, namespace);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("重启Pod失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", "重启Pod失败: " + e.getMessage()));
        }
    }

    /**
     * 删除Pod
     * @param podName Pod名称
     * @param namespace 命名空间（可选）
     * @return 操作结果
     */
    @DeleteMapping("/pods/{podName}")
    public ResponseEntity<Map<String, Object>> deletePod(
            @PathVariable String podName,
            @RequestParam(required = false) String namespace) {
        try {
            Map<String, Object> result = podservice.deletePod(podName, namespace);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("删除Pod失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Collections.singletonMap("error", "删除Pod失败: " + e.getMessage()));
        }
    }

    /**
     * 获取Pod日志（支持指定命名空间）
     * @param podName Pod名称
     * @param namespace 命名空间（可选）
     * @param container 容器名称（可选）
     * @return Pod日志
     */
    @GetMapping("/pods/{podName}/logs")
    public ResponseEntity<String> getK8sPodLogs(
            @PathVariable String podName,
            @RequestParam(required = false) String namespace,
            @RequestParam(required = false) String container) {
        try {
            String logs = podservice.getPodLogs(podName, namespace, container);
            return ResponseEntity.ok(logs);
        } catch (Exception e) {
            log.error("获取Pod日志失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("获取Pod日志失败: " + e.getMessage());
        }
    }


    private KubernetesClient getClient() {
        // 查找 kubeconfig 文件
        File kubeConfigFile = new File(KUBECONFIG_PATH);
        String kubeConfigContents;
        try {
            kubeConfigContents = new String(Files.readAllBytes(kubeConfigFile.toPath()));
        } catch (IOException e) {
            throw new RuntimeException("Unable to read kubeconfig file", e);
        }

        Config config = Config.fromKubeconfig(kubeConfigContents);
        return new DefaultKubernetesClient(config);
    }

    @GetMapping("/pods/{namespace}")
    public Map<String, Object> listPods(@PathVariable String namespace) {
        Map<String, Object> response = new HashMap<>();
        try (KubernetesClient client = getClient()) {
            List<Pod> pods = client.pods().inNamespace(namespace).list().getItems();
            response.put("success", true);
            response.put("pods", pods);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return response;
    }

}
